<template lang="pug">
  el-drawer.commonDrawer(
    :title="`${type === 'add' ? '新增' : type === 'update' ? '修改' : '查看'}学生档案`"
    :visible.sync="visibleDialog"
    v-loading="loading"
    custom-class="commonDrawer"
    direction="rtl"
    size="840px"
    append-to-body
    destroy-on-close
    modal-append-to-body
  )
    .drawer-content
      //el-radio-group.tabTypes.mb20(v-model="curTabKey")
      //  el-radio-button(v-for="tab in tabs" :key="tab.name" :label="tab.name") {{tab.name}}
      .div(v-if="curTabKey === '缴费记录'" ) 缴费记录
      .div(v-if="curTabKey === '基本信息'" )
        form-box(
          ref="basicForm"
          :fields="basicFormFields"
          :showBtns="false"
          labelWidth="126px"
          :disabled="disabled"
          :layoutCol="{ sm: 12, md: 12, lg: 12 }"
          :formProps="basicFormProps"
        )
        el-divider
        form-box(
          ref="parentForm"
          :fields="parentFormFields"
          :showBtns="false"
          labelWidth="126px"
          :disabled="disabled"
          :layoutCol="{ sm: 12, md: 12, lg: 12 }"
          :formProps="basicFormProps"
        )
          .contacts(slot="form-contacts")
            contact-form(v-for="(item, index) in contacts" :key="index" :info="item || {}" ref="contacts" :canDel="true" :type="type" @delContact="contactHandle")
            el-button.mb10(type="success" size="mini" icon="el-icon-circle-plus-outline el-icon--right" @click="() => contactHandle()") 新增
    .drawer-footer.tr(v-if="!disabled")
      el-button.gradientVertical(size="large" round :loading="submitting" @click="submitHandle") 确定
</template>
<script>
import shortid from 'shortid'
import dictMixin from '@/mixins/dict'
import ContactForm from './contact.vue'
import { getChildrenDetail, createChild } from '@/api/common'
import { regs } from '@/utils/validate'
export default {
  components: {
    ContactForm
  },
  mixins: [dictMixin],
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    type: {
      default: 'add',
      type: String
    },
    id: {
      type: [String, Number],
      default: ''
    }
  },
  data () {
    return {
      submitting: false,
      loading: false,
      info: {},
      extend: {},
      contacts: [],

      curTabKey: '基本信息',
      tabs: [
        {
          name: '基本信息'
        },
        {
          name: '缴费记录'
        }
      ]
    }
  },
  computed: {
    visibleDialog: {
      get () {
        return this.visible
      },
      set (val) {
        this.$emit('update:visible', val)
      }
    },
    disabled () {
      return this.type === 'view'
    },
    basicFormProps () {
      return {
        disabled: this.type === 'view'
      }
    },
    basicFormFields () {
      const { info, extend } = this
      const formFileds = [
        {
          key: 'name',
          label: '孩子姓名',
          rules: [{ required: true, message: '请输入' }],
          initialValue: info.name
        },
        {
          key: 'nickName',
          label: '昵称',
          initialValue: info.nickName
        },
        {
          key: 'gender',
          label: '性别',
          initialValue: info.gender?.toString(),
          type: 'select',
          rules: [{ required: true, message: '请输入' }],
          fieldProps: {
            dictKey: 'sex',
            props: { value: 'value', label: 'label' }
          }
        },
        {
          key: 'birthday',
          label: '出生年月',
          type: 'date',
          formatFlag: true,
          rules: [{ required: true, message: '请输入' }],
          initialValue: info.birthday
        },
        {
          key: 'idCard',
          label: '身份证号码',
          rules: [{ required: false, message: '请输入' }, { pattern: regs.idcard, message: '请输入正确的身份证号' }],
          initialValue: info.idCard
        },
        {
          key: 'registerResidence',
          label: '户口所在地',
          initialValue: info.household
        },
        {
          key: 'nationality',
          label: '国籍',
          initialValue: info.nationality
        },
        {
          key: 'targetGarden',
          label: '目标幼儿园',
          initialValue: info.targetGarden
        },
        {
          key: 'bloodType',
          label: '血型',
          type: 'select',
          initialValue: info.bloodType,
          fieldProps: {
            dictKey: 'bloodType',
            props: { value: 'value', label: 'label' }
          }
        },
        {
          key: 'registerType',
          label: '儿童户籍类型',
          type: 'select',
          initialValue: info.registerType,
          fieldProps: {
            dictKey: 'registerType',
            props: { value: 'value', label: 'label' }
          }
        },
        {
          key: 'languageEnvironment',
          label: '孩子语言环境',
          initialValue: info.language
        },
        {
          key: 'cameraValidTo',
          label: '监控有效期',
          type: 'date',
          formatFlag: true,
          initialValue: extend.cameraValidTo
        },
        {
          key: 'imgUrl',
          label: '头像',
          type: 'updateImg',
          formatFlag: true,
          initialValue: info.imgUrl
        }
      ]
      // if (this.type === 'add') {
      //   formFileds.push(
      //     {
      //       key: 'nursyValidTo',
      //       label: '托班有效期',
      //       type: 'date',
      //       formatFlag: true,
      //       rules: [{ required: false, message: '请输入' }]
      //     }
      //   )
      // } else {
      //   formFileds.push(
      //     {
      //       key: 'nurseryEndDate',
      //       label: '托班有效期',
      //       type: 'date',
      //       formatFlag: true,
      //       rules: [{ required: false, message: '请输入' }],
      //       initialValue: extend.nurseryEndDate,
      //       fieldProps: {
      //         disabled: true
      //       }
      //     }
      //   )
      // }

      return formFileds
    },
    parentFormFields () {
      return [
        {
          type: 'slot',
          label: '其他联系人',
          layoutCol: { sm: 24, md: 24, lg: 24 },
          key: 'contacts'
        }
      ]
    }
  },
  watch: {
    visible (val) {
      if (val) {
        this.getChildrenDetail()
      }
    }
  },
  methods: {
    // 新增得时候获取宝宝信息
    getChildrenDetail () {
      if (this.id) {
        this.loading = true
        getChildrenDetail({ childrenId: this.id }).then(res => {
          this.info = {
            ...res?.children
          }
          this.extend = {
            ...res?.extend
          }
          this.contacts = res?.users || []
        }).finally(() => {
          this.loading = false
        })
      } else {
        this.contacts = []
        this.info = {}
        this.contactHandle()
      }
    },
    contactHandle (id) {
      let { contacts } = this
      if (!id) {
        contacts.push({
          id: shortid.generate(),
          fake: true
        })
      } else {
        contacts = contacts.filter(x => x.id !== id)
      }
      this.contacts = contacts
    },
    async submitHandle () {
      const values = await this.$refs.basicForm.submitForm()

      const list = []
      for (const index in this.$refs.contacts) {
        const ref = this.$refs.contacts[index]
        const contactValues = await ref.$refs.contactForm.submitForm()
        list.push(contactValues)
      }
      if (list.length === 0) {
        this.$message.info('请至少添加一位联系人')
        return
      }

      if (!values.nursyValidTo) {
        delete values.nursyValidTo
      }

      const params = {
        ...values,
        linkMans: [...list]
      }
      if (this.type === 'edit') {
        params.childrenId = this.id
      }
      console.log(params)
      this.submitting = true
      createChild(params).then(res => {
        if (res) {
          this.$message.success('保存成功')
          this.$emit('getList')
          this.$_handleCancel()
        }
      }).finally(() => {
        this.submitting = false
      })
    },
    $_handleCancel () {
      this.visibleDialog = false
    }
  }
}
</script>
<style lang="scss" scoped>
.content{
  padding: 0 24px;
  height: calc(100vh - 76px);
  overflow-y: auto;
}
</style>
